package com.hxy.subject.domain.service.impl;

import com.hxy.subject.domain.convert.SubjectLabelConverter;
import com.hxy.subject.domain.entity.SubjectLabelBO;
import com.hxy.subject.domain.service.ISubjectLabelDomainService;
import com.hxy.subject.infra.basic.entity.SubjectLabel;
import com.hxy.subject.infra.basic.entity.SubjectMapping;
import com.hxy.subject.infra.basic.mapper.SubjectMappingDao;
import com.hxy.subject.infra.basic.service.SubjectLabelService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author haoxuyang
 * @Date 2024/9/3 17:28
 */
@Service
public class SubjectLabelDomainServiceImpl implements ISubjectLabelDomainService {
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectMappingDao subjectMappingDao;

    public void add(SubjectLabelBO bo) {
        SubjectLabel subjectLabel = SubjectLabelConverter.INSTANCE.subjectLabelBoToCategory(bo);
        subjectLabelService.insert(subjectLabel);
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(bo.getCategoryId());
        subjectMapping.setLabelId(subjectLabel.getId());
        subjectMapping.setIsDeleted(0);
        subjectMappingDao.insert(subjectMapping);
    }

    public void update(SubjectLabelBO bo) {
        SubjectLabel subjectLabel = SubjectLabelConverter.INSTANCE.subjectLabelBoToCategory(bo);
        subjectLabelService.update(subjectLabel);
    }

    public void delete(SubjectLabelBO bo) {
        SubjectLabel subjectLabel = SubjectLabelConverter.INSTANCE.subjectLabelBoToCategory(bo);
        subjectLabel.setIsDeleted(1);
        subjectLabelService.update(subjectLabel);
    }

    public List<SubjectLabelBO> queryLabelByCategoryId(SubjectLabelBO bo) {
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(bo.getCategoryId());
        List<SubjectMapping> mappingList = subjectMappingDao.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)) {
            return new ArrayList<SubjectLabelBO>();
        }
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        SubjectLabel subjectLabel = new SubjectLabel();
        subjectLabel.setLabelIds(labelIdList);
        List<SubjectLabel> subjectLabelList = subjectLabelService.queryLabelByCategoryId(subjectLabel);
        List<SubjectLabelBO> subjectLabelBOList = SubjectLabelConverter.INSTANCE.subjectLabelToBoList(subjectLabelList);
        return subjectLabelBOList;
    }

}
